package com.mall.admin;

import com.mall.admin.interfaces.AnnotationParse;
import com.mall.user.entity.User;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import javax.servlet.http.HttpSession;
import com.mall.commondataformat.R;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;

import static com.mall.commonutils.SessionStaticMes.USER_IN_SESSION;

/**
 * @description 权限配置AOP实现类,AOP+注解,实现权限拦截校验
 * @author Riskre
 */
@Aspect
@Component
public class BrokerAspect {
    /**
     * 定义切入点，切入点为com.mall.admin.AdminController中的所有函数
     *通过@Pointcut注解声明频繁使用的切点表达式
     */
    @Pointcut( "execution(public * com.mall.admin.AdminController.*(..))")
    public void BrokerAspect(){

    }
    /**
     * @description  执行方法前的拦截方法
     */
    @ResponseBody
    @Around("BrokerAspect()")
    public Object doBeforeAdmin(ProceedingJoinPoint joinPoint) throws Throwable {

        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        //得到方法的访问权限
        final String methodAccess = AnnotationParse.privilegeParse(targetMethod);

        //如果该方法上没有权限注解，直接调用目标方法
        if(StringUtils.isBlank(methodAccess)){
            return joinPoint.proceed();
        }else{
            //获取当前session
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpSession session=attr.getRequest().getSession(true);
            User user = (User) session.getAttribute(USER_IN_SESSION);

            if (user != null) {
                int role = user.getRole();
                if (role == 1) {
                    return R.error().message("无管理员权限");
                }else {
                    return joinPoint.proceed();
                }
            } else {
                return R.error().message("无管理员权限");
            }
        }
    }

}
